package org.xiaov.lunasql.engine.ast.adjust;

import com.alibaba.druid.sql.ast.SQLName;
import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.statement.*;
import org.dromara.hutool.core.text.StrUtil;
import org.xiaov.lunasql.engine.ast.WithRecursiveAsAdjust;

import java.util.List;

/**
 * <p>
 * WithRecursiveAs2WithAsAdjust
 * </p>
 *
 * @author lzq
 * @since 2024/12/23 16:43
 */
public class WithRecursiveAs2WithAsAdjust implements WithRecursiveAsAdjust {

    @Override
    public void adjust(SQLWithSubqueryClause x) {
        x.setRecursive(false);
    }

    /**
     * 转换 with recursive entry
     *
     * @param x x
     */
    @Override
    public void adjustEntry(SQLWithSubqueryClause.Entry x) {
        SQLSelect subQuery = x.getSubQuery();
        if (subQuery != null && subQuery.getQuery() instanceof SQLUnionQuery unionQuery) {
            //拿出第一个查询的参数放入with中
            SQLSelectQuery sqlSelectQuery = unionQuery.getRelations().get(0);
            if (sqlSelectQuery instanceof SQLSelectQueryBlock selectQueryBlock) {
                List<SQLSelectItem> selectList = selectQueryBlock.getSelectList();
                for (SQLSelectItem item : selectList) {
                    String alias = item.getAlias();
                    if (StrUtil.isNotEmpty(alias)) {
                        x.getColumns().add(new SQLIdentifierExpr(alias));
                        continue;
                    }
                    if (item.getExpr() instanceof SQLName sqlName) {
                        x.getColumns().add(sqlName);
                        continue;
                    }
                    x.getColumns().add(new SQLIdentifierExpr(item.getExpr().toString()));
                }
            }
        }
    }
}
